<template>
    <yh-dialog
        :title="staticResultQueryDialogVO.title"
        :visible.sync="staticResultQueryDialogVO.visible"
        drag
        :close-on-click-modal="false"
        :close-on-press-escape="false"
    >
        <el-form label-width="130px" v-model="staticResultQueryReqVO" style="margin: 10px">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="流水号" props="resultId">
                        <el-input name="流水号" v-model="staticResultQueryReqVO.resultId" placeholder="" size="mini"></el-input>
                    </el-form-item>
                    <el-form-item label="静态条目KEY">
                        <el-input name="静态条目KEY" v-model="staticResultQueryReqVO.entryKey" placeholder="" size="mini"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">

                    <el-form-item label="连续违规天数">
                        <el-input name="连续违规天数" v-model.number="staticResultQueryReqVO.prohibitionDate" placeholder="" size="mini"></el-input>
                    </el-form-item>
                    <el-form-item label="触警类型" prop="triggerType">
                        <el-select name="触警类型" v-model="staticResultQueryReqVO.triggerTypeList" collapse-tags multiple filterable size="mini">
                            <!-- <el-option key="" label="" value="" name="triggerType"></el-option> -->
                            <el-option
                                v-for="item in ThresholdTypes"
                                :key="item.dictKey"
                                :label="item.dictKey + ' ' + item.dictKeyName"
                                :value="item.dictKey"
                                :name="'triggerType' + item.dictKey"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-divider></el-divider>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="银行代码">
                        <el-select
                            name="银行代码"
                            placeholder="请选择"
                            v-model="staticResultQueryReqVO.reBankCode"
                            filterable
                            clearable
                            size="mini"
                            v-loading="selectLoading"
                            remote
                            :remote-method="getBankDictList"
                        >
                            <el-option
                                v-for="item in bankDictList"
                                :key="item.dictKey"
                                :label="item.dictKey + ' ' + item.dictKeyName"
                                :value="item.dictKey"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="证券代码" props="reStockCode">
                        <el-select
                            name="证券代码"
                            placeholder="请选择"
                            v-model="staticResultQueryReqVO.reStockCode"
                            filterable
                            clearable
                            size="mini"
                            remote
                            v-loading="selectLoading"
                            :remote-method="getStockDictList"
                        >
                            <el-option
                                v-for="item in stockDictList"
                                :key="item.dictKey"
                                :label="item.dictKey + ' ' + item.dictKeyName"
                                :value="item.dictKey"
                            >
                            </el-option>
                        </el-select> </el-form-item
                ></el-col>
                <el-col :span="12">
                    <el-form-item label="发行人代码">
                        <el-select
                            name="发行人代码"
                            placeholder="请选择"
                            v-model="staticResultQueryReqVO.reIssueCode"
                            filterable
                            clearable
                            size="mini"
                            v-loading="selectLoading"
                            remote
                            :remote-method="getIssueDictList"
                            element-loading-text="加载中"
                        >
                            <el-option
                                v-for="item in issueDictList"
                                :key="item.dictKey"
                                :label="item.dictKey + ' ' + item.dictKeyName"
                                :value="item.dictKey"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-switch
                        active-color="#2589f5"
                        inactive-color="#ccc"
                        active-text="是否显示最新"
                        v-model="staticResultQueryReqVO.showNewRecord"
                        :inactive-value="null"
                        active-value="1"
                        style="margin-left: 80px"
                        size="mini"
                        v-show="isHistory"
                    >
                    </el-switch>
                    <el-form-item label="事件状态" v-show="!isHistory">
                        <el-select name="事件状态" placeholder="请选择" v-model="staticResultQueryReqVO.staticProcessStatus" clearable size="mini">
                            <el-option key="" value="" label="" name="status"></el-option>
                            <el-option
                                v-for="item in processStatus"
                                :key="item.dictKey"
                                :label="item.dictKeyName"
                                :value="item.dictKey"
                                :name="'status' + item.dictKey"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <div slot="footer">
            <el-button @click="staticResultQueryDialogClosed">取 消</el-button>
            <el-button @click="staticResultQueryDialogReset">重 置</el-button>
            <el-button type="primary" @click="staticResultQueryDialogConfirm">确 认</el-button>
        </div>
    </yh-dialog>
</template>
<script lang="ts">
import RiskCustomSelect from '@/common/components/risk-custom-select.vue';
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import { DialogVO } from '@yhfin/biz';
import { Component, Prop, Vue } from 'vue-property-decorator';
import XEUtils from 'xe-utils';
import Dict from '@/pages/static/dict/index.ts';
import * as moment from 'moment';
import { changeOptions, getConfigItem } from '@/utils/tools';
@Component({
    name: 'StaticResultDetailSearch',
    components: {
        RiskCustomSelect,
    },
})
export default class StaticResultDetailSearch extends Vue {
    SHOW_SECURITY = getConfigItem('SHOW_SECURITY');

    @Prop() reqVO;
    @Prop() staticResultQueryDialogVO: DialogVO;
    @Prop() editableTabsValue: string;
    @Prop() showErrorType: boolean;
    // 是否为历史详情
    @Prop() isHistory: boolean;

    private staticResultQueryReqVO: any = {};
    // 账户组
    private fundGroups: any[] = [];
    // 条目编号
    private entryCodes: string = '';

    private reqModel = {
        calculateDateEnd: '',
        calculateDateStart: '',
        entryCodes: '',
        entryGroups: [],
        entryKey: '',
        entryName: '',
        excludeEntryGroup: false,
        fundGroups: [],
        paging: { total: 0, currentPage: 1, totalPage: 0, pageSize: 50 },
        prohibitionDate: '',
        reBankCode: '',
        reFundCode: [],
        reAssetCode: [],
        reFdAcCode: [],
        reIssueCode: '',
        reStockCode: '',
        resultId: '',
        showNewRecord: '1',
        tradeDateEnd: XEUtils.toDateString(new Date(), 'yyyyMMdd'),
        tradeDateStart: XEUtils.toDateString(new Date(), 'yyyyMMdd'),
        triggerTypeList: ['3'],
        precision: false,
    };

    // 估值日期
    private tradeDate = {
        tradeDateStart: XEUtils.toDateString(new Date(), 'yyyyMMdd'),
        tradeDateEnd: XEUtils.toDateString(new Date(), 'yyyyMMdd'),
    };

    // 计算日期
    private calulateDate = {
        calculateDateStart: '',
        calculateDateEnd: '',
    };

    // 字典类
    private resetData: any = {};
    private ThresholdType = Dict.ThresholdType;
    private CompareDirection = Dict.CompareDirection;
    private EntryType = Dict.EntryType;
    private ruleLevelType = Dict.ruleLevelType;
    private stateType = Dict.stateType;

    // 产品
    private funds: any = [];
    // 条目组
    private entryGroup: any = [];
    // 触警类型
    private ThresholdTypes: any = [];

    private processStatus: any = [
        {
            dictKey: '-1',
            dictKeyName: '发起失败',
        },
        {
            dictKey: '0',
            dictKeyName: '未发起',
        },
        {
            dictKey: '1',
            dictKeyName: '已发起',
        },
        {
            dictKey: '2',
            dictKeyName: '无需发起',
        },
        {
            dictKey: '3',
            dictKeyName: '已有风险事件',
        },
    ];

    private stockDictList: any[] = []; // 证券代码下拉选项

    private bankDictList: any[] = []; // 银行代码下拉选项

    private issueDictList: any[] = []; // 发行人代码下拉选项

    private selectLoading: boolean = false; // 下拉选项加载

    private key: number = -1; // 下拉多选
    assetList: any = [];
    fdAcList: any[] = [];

    FundTypes: any[] = [];
    fundProducts: any[] = [];

    async mounted() {
        if (this.SHOW_SECURITY) {
            this.$axios.get('/asset/list/byFundCode').then((res: any) => {
                this.assetList = res;
            });
            this.$axios.get('/fdAc/list/byFundCode').then((res: any) => {
                this.fdAcList = res;
            });
        }

        this.staticResultQueryReqVO = JSON.parse(JSON.stringify(this.reqVO));
        // this.processAuth = this.processAuth || [];
        // 触警类型
        if (this.showErrorType) {
            this.ThresholdTypes = DictionConstUtil.PojoToList(DictionConstUtil.ThresholdType);
        } else {
            this.ThresholdTypes = DictionConstUtil.PojoToList(DictionConstUtil.ThresholdType).filter(item => item.dictKey != '4');
        }

        // 获取产品代码组
        let fundInfo = await SGU_CACHE('FundInfoByUser', '/fundInfo/list/byUser/like', []);
        this.funds = XEUtils.map(fundInfo, item => {
            return { dictKey: item.fundCode, dictKeyName: item.fundNameSt, showCode: item.showCode };
        });
        this.fundProducts = XEUtils.map(fundInfo, item => {
            return { dictKey: item.fundProductCode, dictKeyName: item.fundNameSt, showCode: item.showCode };
        });

        // 账户组信息
        let fundGroups = (await DictionConstUtil.FNFundGroup()) || [];
        for (let i = 0; i < fundGroups.length; i++) {
            this.fundGroups.push({ dictKey: fundGroups[i].fundGroupCode, dictKeyName: fundGroups[i].fundGroupName });
        }

        // 条目组
        this.$axios.get('/entry/group/list').then((res: any) => {
            res = res || [];
            for (let i = 0; i < res.length; i++) {
                this.entryGroup.push({ dictKey: res[i].groupCode, dictKeyName: res[i].groupName });
            }
            this.key++;
        });

        // 初始化证券下拉 初始化银行下拉 初始化发行人下拉
        await this.getStockDictList('');
        await this.getIssueDictList('');
        await this.getBankDictList('');

        this.resetData = XEUtils.clone(this.staticResultQueryReqVO, true);
        this.entryCodes = this.staticResultQueryReqVO.entryCodes ? this.staticResultQueryReqVO.entryCodes.join(';') : '';
        this.dateHandleReset();

        this.FundTypes = await SGU_CACHE('FundType', '/dict/list/code/Y_000002', []);
    }

    // 产品代码已选项前置
    get computedFunds() {
        if (this.staticResultQueryReqVO.reFundCode && this.staticResultQueryReqVO.reFundCode.length) {
            let funds = changeOptions(this.staticResultQueryReqVO.reFundCode, this.funds, 'dictKey');
            return funds;
        } else {
            return this.funds;
        }
    }

    // 资产单元已选项前置
    get computedAssetList() {
        if (this.staticResultQueryReqVO.reAssetCode && this.staticResultQueryReqVO.reAssetCode.length) {
            let assetList = changeOptions(this.staticResultQueryReqVO.reAssetCode, this.assetList, 'assetCode');
            return assetList;
        } else {
            return this.assetList;
        }
    }

    // 组合已选项前置
    get computedFdAcList() {
        if (this.staticResultQueryReqVO.reFdAcCode && this.staticResultQueryReqVO.reFdAcCode.length) {
            let fdAcList = changeOptions(this.staticResultQueryReqVO.reFdAcCode, this.fdAcList, 'fundAccountCode');
            return fdAcList;
        } else {
            return this.fdAcList;
        }
    }

    // 账户组已选项前置
    get computedFundGroups() {
        if (this.staticResultQueryReqVO.fundGroups && this.staticResultQueryReqVO.fundGroups.length) {
            let fundGroups = changeOptions(this.staticResultQueryReqVO.fundGroups, this.fundGroups, 'dictKey');
            return fundGroups;
        } else {
            return this.fundGroups;
        }
    }

    // 条目组已选项前置
    get computedEntryGroup() {
        if (this.staticResultQueryReqVO.entryGroups && this.staticResultQueryReqVO.entryGroups.length) {
            let entryGroup = changeOptions(this.staticResultQueryReqVO.entryGroups, this.entryGroup, 'dictKey');
            return entryGroup;
        } else {
            return this.entryGroup;
        }
    }

    // 获取证券代码下拉框选项
    private getStockDictList(e: string): void {
        this.selectLoading = false;
        this.$axios
            .post('/dict/stock/select', {
                dictKey: e,
                dictKeyName: e,
            })
            .then((res: any) => {
                this.stockDictList = res || [];
                this.selectLoading = false;
            })
            .catch(() => {
                this.selectLoading = false;
            });
    }

    // 获取发行人代码下拉框选项
    private getIssueDictList(e: string): void {
        this.selectLoading = false;
        this.$axios
            .post('/dict/issue/select', {
                dictKey: e,
                dictKeyName: e,
            })
            .then((res: any) => {
                this.issueDictList = res || [];
                this.selectLoading = false;
            })
            .catch(() => {
                this.selectLoading = false;
            });
    }

    // 获取银行代码下拉框选项
    private getBankDictList(e: string): void {
        this.selectLoading = false;
        this.$axios
            .post('/dict/bank/select', {
                dictKey: e,
                dictKeyName: e,
            })
            .then((res: any) => {
                this.bankDictList = res || [];
                this.selectLoading = false;
            })
            .catch(() => {
                this.selectLoading = false;
            });
    }

    traderDatePickerS = {
        disabledDate: time => {
            // 开始日期不能比今天大
            let maxDate = new Date().getTime();
            return time.getTime() > maxDate;
        },
    };

    traderDatePickerE = {
        disabledDate: time => {
            let minDate;
            let maxDate;
            if (this.tradeDate.tradeDateStart) {
                const tradeDateStart = moment(this.tradeDate.tradeDateStart).format('yyyy-MM-DD');
                // 结束日期不能比开始日期小
                minDate = Date.parse(tradeDateStart);
                // 结束日期不能跨月
                const year = moment(this.tradeDate.tradeDateStart).year();
                const month = moment(this.tradeDate.tradeDateStart).month() + 1;
                maxDate = new Date(year, month, 0); // 2009年6月的第0天，也就是2009年5月的最后一天。
                // 如果最大日期 比 今天 还大的话  就用今天
                if (maxDate.getTime() > new Date().getTime()) {
                    return time.getTime() > new Date().getTime() || time.getTime() < minDate - 3600 * 1000 * 24;
                }
                return time.getTime() > maxDate || time.getTime() < minDate - 3600 * 1000 * 24;
            }
            // 结束日期不能比今天大
            maxDate = new Date().getTime();
            return time.getTime() > maxDate || time.getTime() < minDate - 3600 * 1000 * 24;
        },
    };

    calcDatePickerS = {
        disabledDate: time => {
            // 开始日期不能比今天大
            let maxDate = new Date().getTime();
            return time.getTime() > maxDate;
        },
    };

    calcDatePickerE = {
        disabledDate: time => {
            let minDate;
            let maxDate;
            if (this.calulateDate.calculateDateStart) {
                const tradeDateStart = moment(this.calulateDate.calculateDateStart).format('yyyy-MM-DD');
                // 结束日期不能比开始日期小
                minDate = Date.parse(tradeDateStart);
                // 结束日期不能跨月
                const year = moment(this.calulateDate.calculateDateStart).year();
                const month = moment(this.calulateDate.calculateDateStart).month() + 1;
                maxDate = new Date(year, month, 0); // 2009年6月的第0天，也就是2009年5月的最后一天。
                // 如果最大日期 比 今天 还大的话  就用今天
                if (maxDate.getTime() > new Date().getTime()) {
                    return time.getTime() > new Date().getTime() || time.getTime() < minDate - 3600 * 1000 * 24;
                }
                return time.getTime() > maxDate || time.getTime() < minDate - 3600 * 1000 * 24;
            }
            // 结束日期不能比今天大
            maxDate = new Date().getTime();
            return time.getTime() > maxDate || time.getTime() < minDate - 3600 * 1000 * 24;
        },
    };

    // 估值开始日期改变
    private tradeDateStartChange(val): void {
        // if (this.tradeDate.tradeDateEnd < val) {
        this.tradeDate.tradeDateEnd = undefined;
        // }
    }

    // 计算开始日期改变
    private calculateDateStartChange(val): void {
        // if (this.calulateDate.calculateDateEnd < val) {
        this.calulateDate.calculateDateEnd = undefined;
        // }
    }

    // 处理条目编号
    private handleEntryCodes(): void {
        this.staticResultQueryReqVO.entryCodes = this.entryCodes.split(',');
    }

    // 关闭弹窗
    private staticResultQueryDialogClosed(): void {
        this.staticResultQueryDialogVO.visible = false;
    }

    // 重置
    private staticResultQueryDialogReset(): void {
        this.staticResultQueryReqVO = JSON.parse(JSON.stringify(this.reqModel));
        // 条目编号
        this.key++;
        this.entryCodes = '';
        this.dateHandleReset();
    }

    // 日期重置
    private dateHandleReset(): void {
        this.tradeDate.tradeDateStart = this.staticResultQueryReqVO.tradeDateStart.toString();
        this.tradeDate.tradeDateEnd = this.staticResultQueryReqVO.tradeDateEnd.toString();

        this.calulateDate.calculateDateStart =
            this.staticResultQueryReqVO.calculateDateStart === 0 ? '' : this.staticResultQueryReqVO.calculateDateStart.toString();
        this.calulateDate.calculateDateEnd =
            this.staticResultQueryReqVO.calculateDateEnd === 0 ? '' : this.staticResultQueryReqVO.calculateDateEnd.toString();
    }

    // 计算日期处理
    private dateTrans(selectValue): void {
        let sendValue;
        if (!selectValue) {
            sendValue = 0;
        } else {
            sendValue = parseInt(selectValue);
        }
        return sendValue;
    }

    // 确定
    private staticResultQueryDialogConfirm(): void {
        if (this.staticResultQueryDialogVO.title == '静态历史结果高级查询') {
            // 历史tab
            this.staticResultQueryReqVO.calculateDateStart = this.dateTrans(this.calulateDate.calculateDateStart);
            this.staticResultQueryReqVO.calculateDateEnd = this.dateTrans(this.calulateDate.calculateDateEnd);
            this.staticResultQueryReqVO.tradeDateStart = this.dateTrans(this.tradeDate.tradeDateStart);
            this.staticResultQueryReqVO.tradeDateEnd = this.dateTrans(this.tradeDate.tradeDateEnd);

            // 计算日期暂未进行必选项处理
            if (!this.staticResultQueryReqVO.tradeDateStart || !this.staticResultQueryReqVO.tradeDateEnd) {
                this.$message.error('估值日期不可为空');
                return;
            }
        }

        this.$emit('staticResultQueryReturn', this.staticResultQueryReqVO);
        this.staticResultQueryDialogClosed();
    }

    // 下拉多选返回值
    private customSelectReturn(value: any, type: string): void {
        this.staticResultQueryReqVO[type] = value;
    }
}
</script>
<style lang="scss" scoped>
/deep/ .el-dialog {
    min-width: 910px;
    .el-dialog__body {
        padding: 0 70px 0px 0 !important;
        margin: 20px 0px;
    }
}
/deep/ .el-form-item {
    margin-bottom: 0 !important;
}
/deep/ .el-select {
    width: 100%;
}
.ruleId {
    display: flex;
    justify-content: space-between;
    .actual-search {
        background-color: #f2f2f2;
        padding: 0 6px;
        border-radius: 8%;
        line-height: 32px;
        height: 32px;
        margin: 5px;
    }
}
/deep/ .el-checkbox .el-checkbox__input.is-checked .el-checkbox__inner {
    background-color: #409eff !important;
    &:after {
        border-color: #fff !important;
    }
}
/deep/ .el-checkbox__inner {
    border-color: #409eff;
}
// // 日期选择期
// .el-range-editor.is-active {
//   border-color: #409eff;
// }
// /deep/ .el-date-editor {
//   height: 32px !important;
//   .el-range-separator {
//     width: 9% !important;
//   }
//   .el-range__close-icon,
//   .el-range__icon,
//   .el-range-separator {
//     line-height: 26px !important;
//   }
// }
</style>
